import { defineStore } from "pinia";
import { reactive, toRefs } from "vue";
import { store } from ".";

let timeId: NodeJS.Timeout;
const useAppStore = defineStore("app", () => {
  const state = reactive({ loading: false });

  /** 立即设置页面为loading状态 */
  const setPageLoading = (loading: boolean) => {
    state.loading = loading;
  };

  /** 设置页面为loading状态 */
  const setPageLoadingAction = async (loading: boolean) => {
    if (loading) {
      clearTimeout(timeId);
      timeId = setTimeout(() => {
        setPageLoading(loading);
      }, 50);
    } else {
      setPageLoading(loading);
      clearTimeout(timeId);
    }
  };

  return {
    ...toRefs(state),
    setPageLoading,
    setPageLoadingAction,
  };
});

/**
 * @description 应用全局状态 (在setup方法外使用此方法)
 */
export function useAppStoreWithOut() {
  return useAppStore(store);
}
